package com.study.io.nio.demo.buffer;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.MessageFormat;

/**
 * RandomAccessFile demo
 * 与传统io相比可实现读写并且部分读取,可用于断点下载等等
 *
 * @author wuxj
 */
public class RandomAccessFileDemo {

    public static void main(String[] args) {
        //通过RandomAccessFile读取文件 IO处理
        try {
            RandomAccessFile rf = new RandomAccessFile("d://321.txt", "rw");

            //调整指针位置
            rf.seek(0);
            long start = System.currentTimeMillis();
            byte[] b = new byte[6];
            rf.read(b);
            System.out.println(new String(b));
            System.out.println(System.currentTimeMillis() - start);

            System.out.println(MessageFormat.format("当前位置：{0}", rf.getFilePointer()));

            //写入内容
            rf.write("咳咳".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }

        //通过RandomAccessFile读取文件 通道处理
        try {
            RandomAccessFile rf = new RandomAccessFile("d://321.txt", "rw");
            FileChannel fc = rf.getChannel();

            //读出文件内容
            long start = System.currentTimeMillis();
            ByteBuffer buffer = ByteBuffer.allocate(6);
            fc.read(buffer);
            byte[] b = buffer.array();
            System.out.println(new String(b));
            System.out.println(System.currentTimeMillis() - start);

            //写入文件内容
            buffer.clear();
            buffer.put("拉拉".getBytes());
            buffer.flip();
            fc.write(buffer);

            buffer.clear();
            rf.close();
            fc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
